package com.cat.dynamicPlanning;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/russian-doll-envelopes/description/
 * @create 2025/9/3 21:12
 * @since JDK17
 */

public class Solution63 {
    int[] ends;
    int[][] enve;
    int f(int n, int t) {
        int l = -1, r = n, mid;
        while (l + 1 < r) {
            mid = (l + r) / 2;
            if (enve[ends[mid]][1] >= t) {
                r = mid;
            } else {
                l = mid;
            }
        }
        return r;
    }

    public int maxEnvelopes(int[][] envelopes) {
        Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
        int n = envelopes.length, cnt = 1;
        ends = new int[n];
        ends[0] = 0;
        enve = envelopes;
        for (int i = 1; i < n; i++) {
            int j = f(cnt, enve[i][1]);
            if (j == cnt && (enve[i][0] == enve[ends[cnt - 1]][0] || enve[i][1] == enve[ends[cnt - 1]][1])) {
                continue;
            }
            ends[j] = i;
            cnt += j == cnt ? 1 : 0;
        }

        return cnt;
    }
}
